// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: 'ai-tell-9gawh557896fca1d' }) // 使用当前云环境
const APPID = '68331129'
const APISecret = 'YmM5ZjlhODY4MDg0NDc0YzBlOWNiZWY3'
const APIKey = '9dc4c903576f196af12a82824d1ca456'
const base64 = require('base-64')
const CryptoJS = require('crypto-js')

// 云函数入口函数
exports.main = async (event, context) => {
  var url = "wss://spark-api.xf-yun.com/v4.0/chat";
  var host = "spark-api-open.xf-yun.com";
  var apiKeyName = "api_key";
  var date = new Date().toGMTString();
  var algorithm = "hmac-sha256";
  var headers = "host date request-line";
  var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v4.0/chat HTTP/1.1`;
  var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, APISecret);
  var signature = CryptoJS.enc.Base64.stringify(signatureSha);
  var authorizationOrigin =
    `${apiKeyName}="${APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
  var authorization = base64.encode(authorizationOrigin);
  url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;
  return {APPID,url}
}